package com.kuaimacode.kframework.agent.controller.master;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.kuaimacode.kframework.agent.services.agent.SysAgentService;
import com.kuaimacode.kframework.agent.services.finance.AgentAccountDetailService;
import com.kuaimacode.kframework.agent.services.master.MasterService;
import com.kuaimacode.kframework.agent.services.oplog.SysOpLogService;
import com.kuaimacode.kframework.agent.services.order.OrderService;
import com.kuaimacode.kframework.agent.services.role.SysAgentRoleService;
import com.kuaimacode.kframework.agent.services.role.UserMapRoleService;
import com.kuaimacode.kframework.agent.services.role.UserRoleService;
import com.kuaimacode.kframework.agent.services.serv.AgentServService;
import com.kuaimacode.kframework.agent.services.user.UserService;
import com.kuaimacode.kframework.agent.vo.request.HistoryReq;
import com.kuaimacode.kframework.agent.vo.request.MasterReq;
import com.kuaimacode.kframework.agent.vo.request.OrderReq;
import com.kuaimacode.kframework.agent.vo.response.HistoryOpLog;
import com.kuaimacode.kframework.common.JsonResult;
import com.kuaimacode.kframework.constants.PageConstants;
import com.kuaimacode.kframework.mybatis.mapper.user.UserAccountDetailMapper;
import com.kuaimacode.kframework.mybatis.models.agent.SysAgent;
import com.kuaimacode.kframework.mybatis.models.category.AgentServ;
import com.kuaimacode.kframework.mybatis.models.finance.AgentAccountDetail;
import com.kuaimacode.kframework.mybatis.models.master.MasterMessage;
import com.kuaimacode.kframework.mybatis.models.master.MasterMessageCh;
import com.kuaimacode.kframework.mybatis.models.master.UserMaster;
import com.kuaimacode.kframework.mybatis.models.master.UserMasterData;
import com.kuaimacode.kframework.mybatis.models.sys.Dict;
import com.kuaimacode.kframework.mybatis.models.sys.SysOpLog;
import com.kuaimacode.kframework.mybatis.models.user.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author Administrator
 * @date 2019/04/06
 */

/**
 * Controller
 */
@Controller
@RequestMapping({"/master"})
public class MasterController {
	private static String PAGE_FILE_NAME = "master/";

	@Autowired
	private MasterService masterServices;

	@Autowired
	private UserRoleService roleService;

	@Autowired
	private UserMapRoleService mapRoleService;

	@Autowired
	private UserService  userService;

	@Autowired
	private SysOpLogService opLogService;

	@Autowired
	private OrderService orderService;

	@Autowired
	AgentServService agentServService;

	@Autowired
	UserAccountDetailMapper detailMapper;

	@Autowired
	SysAgentService agentService;

	@Autowired
	AgentAccountDetailService agentAccService;

	@Value("${img.upload.location.img}")
	private String imgUploadLocation;
	@Value("${project.domain}")
	private String domain;


	@RequestMapping(value = {"/index"})
	public String index(@RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM+"") int pageNum,
						@RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE+"") int pageSize,
						MasterReq masterReq, ModelMap model) {
		PageInfo<UserMasterData> pageInfo = masterServices.findMasterAll(masterReq,pageNum, pageSize);
		// pageInfo.list master
		model.put("pageInfo", pageInfo);
		model.put("masterReq", masterReq);
		return PAGE_FILE_NAME + "index";
	}

	@RequestMapping(value = {"/history/{userId}"})
	public String history(@RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM+"") int pageNum,
						 @RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE+"") int pageSize,
						 @PathVariable long userId,HistoryReq req ,ModelMap model) {
//		UserMaster master = masterServices.getById(id);
		PageInfo<HistoryOpLog> pageInfo = opLogService.findHistory(pageNum, pageSize,userId,req);
		// pageInfo.list master
		model.put("pageInfo", pageInfo);
		model.put("historyReq", req);
		model.put("userId",userId);
		return PAGE_FILE_NAME + "history";
	}

	@RequestMapping(value = {"/online/{ids}/{userId}"})
	public String online(@RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM+"") int pageNum,
						@RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE+"") int pageSize,
						@PathVariable String ids,@PathVariable Long userId, ModelMap model) {
		PageInfo<SysOpLog> pageInfo = opLogService.findAll(pageNum, pageSize,ids,userId);
		// pageInfo.list master
		MasterReq masterReq = new MasterReq();
		model.put("pageInfo", pageInfo);
		model.put("masterReq", masterReq);
		model.put("userId",userId);
		model.put("ids",ids);
		return PAGE_FILE_NAME + "online";
	}


	@RequestMapping(value = "/agree/{id}", method = RequestMethod.POST)
	@Transactional
	@ResponseBody
	public JsonResult add(@PathVariable String id, ModelMap map) {
		if (agreeOp(Long.parseLong(id))){
			return JsonResult.success();
		}else{
			return JsonResult.failure("申请操作失败");
		}

	}


	private boolean agreeOp(long id){
		try {
			UserMaster master = masterServices.getById(id);
			if (master!=null){
				master.setAuthStatus("1");
				if (masterServices.updateById(master)){
					//查找角色
					QueryWrapper<UserRole> rolw = new QueryWrapper<>();
					rolw.eq("role_name","ROLE_MASTER");
					UserRole ro= roleService.getOne(rolw);
					String[] permissionIds = {String.valueOf(ro.getId())};
					//分配角色
					mapRoleService.grantRole(String.valueOf(master.getUserId()),permissionIds);
					//更新用户表
					User user = userService.getById(master.getUserId());
					if (user !=null){
						user.setIsMaster(2);
						userService.updateById(user);
					}
				}
			}
			return true;
		}catch (Exception ex){
			return false;
		}
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String edit(@PathVariable String id, ModelMap map) {
		UserMaster master = masterServices.getById(id);
		map.put("master", master);
		map.put("isAdd", false);
		return PAGE_FILE_NAME+"form";
	}

	@RequestMapping(value = {"/edit"}, method = RequestMethod.POST)
	@ResponseBody
	public JsonResult edit(MasterMessageCh master,ModelMap map) {
		try {
			UserMaster master1 = masterServices.getById(master.getId());
			User user = userService.getById(master1.getUserId());

			BigDecimal balance = new BigDecimal(0);
			//更新余额
			SysAgent agent = agentService.getById(master1.getAgentId());
			//平台余额
			BigDecimal agentBalance = agent.getBalance();
			if (StringUtils.isNotEmpty(master.getDiffAmount())){
				if("1".equals(master.getBalanceStatus())){
					balance = user.getAccountBalance().subtract(new BigDecimal(master.getDiffAmount())).setScale(2,BigDecimal.ROUND_HALF_DOWN);
					//扣减师傅余额，分站金额增加，罚款收入
					agentBalance = agentBalance.add(new BigDecimal(master.getDiffAmount())).setScale(2,BigDecimal.ROUND_HALF_DOWN);
				}else if ("2".equals(master.getBalanceStatus())){
					balance = user.getAccountBalance().add(new BigDecimal(master.getDiffAmount())).setScale(2,BigDecimal.ROUND_HALF_DOWN);
					//增加师傅余额，分站金额减少，奖励支出
					agentBalance = agentBalance.subtract(new BigDecimal(master.getDiffAmount())).setScale(2,BigDecimal.ROUND_HALF_DOWN);
				}
				user.setAccountBalance(balance);
				if (userService.updateById(user)){
					//账户明细
					insertAccountDetail(master1.getUserId(),new BigDecimal(master.getDiffAmount()),master.getBalanceStatus(),balance);
					//分站明细
					agent.setBalance(agentBalance);
					if (agentService.updateById(agent)){
						inserAgentDetail(master1.getUserId(),new BigDecimal(master.getDiffAmount()),master.getBalanceStatus(),master1.getAgentId(),agentBalance);
					}
				}
			}
			//更新技能
			JSONObject object = new JSONObject();
			String serviceType = master.getServiceType();
			if (StringUtils.isNotEmpty(serviceType)){
				String[] args = serviceType.split(",");
				for (String arg : args) {
					if (!arg.contains(":")&&arg.equals("1")){
						object.put(arg,"");
					}else{
						String[] argsplit = arg.split(":");
						String arg_1 = argsplit[0];
						String arg_2 = argsplit[1];
						if (object.containsKey(arg_1)){
							String skill = object.getString(arg_1);
							skill+=","+arg_2;
							object.put(arg_1,skill);
						}else{
							object.put(arg_1,arg_2);
						}
					}
				}
			}
			master1.setSkillType(JSON.toJSONString(object));
			master1.setStatus(master.getStatus());

			masterServices.updateById(master1);
			//更新
			if (StringUtils.isNotEmpty(master.getAuthStatus())){
				if (!String.valueOf(user.getIsMaster()).equals(master.getAuthStatus())){
					//只有不同时才更新
					switch (master.getAuthStatus()){
						case "2":
							//更新用户表
							agreeOp(master1.getId());
							break;
						case "3":
							disAggree(master1.getId());
							break;
						default:
							break;
					}
				}
			}
		} catch (Exception e) {
			return JsonResult.failure(e.getMessage());
		}
		return JsonResult.success();
	}


	@RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
	public String detail(@PathVariable String id, ModelMap map) {
		MasterMessage master = new MasterMessage();
		List<MasterMessage> masters = masterServices.findAllMasterMessage(Long.parseLong(id));
		MasterMessageCh ch = new MasterMessageCh();
		if (CollectionUtils.isNotEmpty(masters)){
			master = masters.get(0);
			if (StringUtils.isNotEmpty(master.getSkillPic())){
				master.setSkillPic(domain+imgUploadLocation+master.getSkillPic());
			}
			if (StringUtils.isNotEmpty(master.getCardPositive())){
				master.setCardPositive(domain + imgUploadLocation+master.getCardPositive());
			}
			if (StringUtils.isNotEmpty(master.getCardNegative())){
				master.setCardNegative(domain + imgUploadLocation+master.getCardNegative());
			}
			if (StringUtils.isNotEmpty(master.getHeadPic())){
				master.setHeadPic(domain + imgUploadLocation+master.getHeadPic());
			}
			JSONObject jobj = JSON.parseObject(master.getSkillType());
			if (jobj.containsKey("1")&&jobj.keySet().size()>1){
				master.setServiceType("2");
			}else if (jobj.containsKey("1")&&jobj.keySet().size()==1){
				master.setServiceType("1");
			}else{
				master.setServiceType("3");
			}
			List<AgentServ> dicts = agentServService.findAgetnServByAgentId(master.getAgentId());
			List<Dict> skillList = new ArrayList<>();
			if (CollectionUtils.isNotEmpty(dicts)){
				dicts.forEach(item->{
					Dict dict = new Dict();
					dict.setId(item.getId());
					dict.setCode(item.getServiceClass()+":"+item.getServiceCode());
					dict.setValue(item.getServiceCode());
					dict.setName(item.getServiceName());
					if (StringUtils.isNotEmpty(jobj.getString(item.getServiceClass()))){
						dict.setLevel(1);//1选中
					}else{
						dict.setLevel(0);
					}
					skillList.add(dict);
				});
			}
			BeanUtils.copyProperties(master,ch);
			ch.setServiceTypeList(skillList);
		}
		map.put("master", ch);
		return PAGE_FILE_NAME+"detail";
	}



	@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult delete(@PathVariable String id, ModelMap map) {
		if (disAggree(Long.parseLong(id))){
			return JsonResult.success();

		}else{
			return JsonResult.failure("驳回申请失败");
		}
	}

	private boolean disAggree(Long id){
		try {
			UserMaster master = masterServices.getById(id);
			if (masterServices.removeById(id)){
				//更改用户认证状态isMaster
				if (master!=null){
					User user = userService.getById(master.getUserId());
					if (user !=null){
						//被驳回状态
						user.setIsMaster(3);
						if (userService.updateById(user)){
							QueryWrapper<UserMapRole> mapRoleQueryWrapper = new QueryWrapper<>();
							mapRoleQueryWrapper.eq("user_id",master.getUserId());
							mapRoleQueryWrapper.eq("role_id",2);
							mapRoleService.remove(mapRoleQueryWrapper);
							return true;
						}
					}
				}
			}
		} catch (Exception e) {
		}
		return false;
	}


	@RequestMapping(value = {"/data/{id}"})
	public String data(@RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM+"") int pageNum,
					   @RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE+"") int pageSize,
					   @PathVariable long id, OrderReq order, ModelMap model) {
		UserMaster master = masterServices.getById(id);
		order.setMasterId(master.getUserId());
		PageInfo<Order> pageInfo = orderService.findAll(pageNum, pageSize, order);
		// pageInfo.list order
		model.put("pageInfo", pageInfo);
		model.put("orderSearch", order);
		model.put("id",id);
		return PAGE_FILE_NAME+"data";
	}


	private boolean insertAccountDetail(Long userId,BigDecimal amount,String type,BigDecimal balance){
		Date date = new Date();
		UserAccountDetail accountDetail = new UserAccountDetail();
		try {
			accountDetail.setUserId(userId);
			accountDetail.setUpdateDt(date);
			accountDetail.setCreateDt(date);
			accountDetail.setInOutType("1".equals(type)?"4":"3");
			accountDetail.setDetailType(type);
			accountDetail.setAmount(String.valueOf(amount));
			accountDetail.setAccountType("1");
			accountDetail.setTranDesc("1".equals(type)?"平台罚款":"平台奖励");
			accountDetail.setAccoutWay(4L);
			accountDetail.setTranAmount(balance);
			detailMapper.insert(accountDetail);
			return true;
		}catch (Exception ex){
			System.out.println("插入账户明细表异常"+ex);
		}
		return false;

	}


	private boolean inserAgentDetail(Long userId,BigDecimal amount,String type,String agentId,BigDecimal tranBal){
		Date date = new Date();
		try {
			AgentAccountDetail agentAccountDetail = new AgentAccountDetail();
			agentAccountDetail.setInOut(!"1".equals(type)?"2":"1");
			agentAccountDetail.setAgentId(agentId);
			agentAccountDetail.setAmount(amount);
			agentAccountDetail.setTranBal(tranBal);
			agentAccountDetail.setTranDesc("1".equals(type)?"平台师傅罚款":"平台师傅奖励");
			agentAccountDetail.setTranTime(date);
			agentAccountDetail.setStatus("0");
			agentAccountDetail.setTranType("1".equals(type)?"13":"12");
			agentAccService.save(agentAccountDetail);
			return true;
		}catch (Exception ex){
			System.out.println("插入账户明细表异常"+ex);
		}
		return false;

	}
}
